<?php
/*
 * 内涵段子的热门段子 请求方式：GET 参数： c=count&p=page 参数c表示请求的条数；参数p表示请求第几页
 */
require_once 'file_php.php';
require_once 'JG_Cache.php';

$kExpiration = 1 * 60;
$kPage = "page";
$kCountKeyword = "count";
$kDate = "date";

$kDefaultType = "history";
$kServerFormatUrls = array(
        $kDefaultType => "http://m2.qiushibaike.com/article/history/%s?page=%s&count=%s"
);

$kDefaultCount = 20;
$kDefaultPage = 1;

$kDataInputTag = "items";
$kDataOutputTag = "data";
$kImageIdKey = "id";
$kImageNameKey = "image";
$kThumbnailUrl = "thumbnailUrl";
$kLargeUrl = "largeUrl";

$kFilterKeys = array(
        "content" => "description",
        "thumbnail_url" => $kThumbnailUrl,
        "large_url" => $kLargeUrl,
        "id" => $kImageIdKey,
        "image" => $kImageNameKey
);
$kThumbnailFormat = "http://img.qiushibaike.com/system/pictures/%s/small/%s";
$kLargeImageFormat = "http://img.qiushibaike.com/system/pictures/%s/medium/%s";

set_time_limit(0);
$page = $_GET[$kPage];
$page = (false == $page) ? $kDefaultPage : $page;

$count = $_GET[$kCountKeyword];
$count = (false == $count) ? $kDefaultCount : $count;

$date = $_GET[$kDate];
$date = (false == $date) ? date('Y-m-d') : $date;

$kServerFormatTxtUrl = $kServerFormatUrls[$kDefaultType];

$reqUrl = sprintf($kServerFormatTxtUrl, $date, $page, $count);

// get cache data
$cache = new JG_Cache('cache'); // Make sure it exists and is writeable
$data = $cache->get($reqUrl, $kExpiration);

if ($data === false) {
    $data = file_php::getRemoteFile($reqUrl);
    
    $data = json_decode($data, true);
    // remove junk data
    $respArray = $data[$kDataInputTag];
    $rearrangeArray = array();
    $current = array();
    foreach ($respArray as $itemArray) {
        foreach ($itemArray as $item => $value) {
            // echo $item . ":" . $value . "<br/>";
            $filterValue = $kFilterKeys[$item];
            if (false != $filterValue) {
                $current[$filterValue] = $value;
                // echo $filterValue . "filterValue:" . $value . "<br/>";
            }
        }
        // add to filtered array
        
        // add thumbnai & large image
        if (false != $current[$kImageIdKey] && false != $current[$kImageNameKey]) {
            $current[$kThumbnailUrl] = sprintf($kThumbnailFormat, 
                    $current[$kImageIdKey], $current[$kImageNameKey]);
            $current[$kLargeUrl] = sprintf($kLargeImageFormat, 
                    $current[$kImageIdKey], $current[$kImageNameKey]);
        }
        $rearrangeArray[] = $current;
    }
    
    // save to cache
    $data = json_encode(
            array(
                    $kDataOutputTag => $rearrangeArray
            ));
    
    $cache->set($reqUrl, $data);
}
echo $data;
?>